package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class ViewBookDetails extends Activity {
	Boolean showAddToWishList = true;
	ProgressThread progThread;
	final int SPINNER = 0;
	ProgressDialog progDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_book_details);

		final Bundle extras = this.getIntent().getExtras();
		final String data = extras.getString("data");
		String titleString = null;
		String editionString = null;
		String coursesString = null;
		String authorsString = null;
		String publishersString = null;
		String isbnString = null;
		JSONArray goodConditionArray = null;
		JSONArray likenewConditionArray = null;
		JSONArray fairConditionArray = null;

		try {
			JSONArray jArray = new JSONArray(data);
			JSONObject currentBook = jArray.getJSONObject(0);
			titleString = currentBook.getString("Title");
			editionString = currentBook.getString("Edition");
			coursesString = currentBook.getString("Courses");
			authorsString = currentBook.getString("Authors");
			publishersString = currentBook.getString("Publisher");
			isbnString = currentBook.getString("ISBN");
			goodConditionArray = currentBook.getJSONArray("CopyGood");
			likenewConditionArray = currentBook.getJSONArray("CopyLikeNew");
			fairConditionArray = currentBook.getJSONArray("CopyFair");
			
			if((fairConditionArray.length() + likenewConditionArray.length() + goodConditionArray.length())!=0)
				showAddToWishList = false;

			TextView title = (TextView) findViewById(R.id.title);
			title.setText(titleString);

			TextView edition = (TextView) findViewById(R.id.edition);
			edition.setText(editionString);

			TextView courses = (TextView) findViewById(R.id.courses);
			courses.setText(coursesString);

			TextView authors = (TextView) findViewById(R.id.authors);
			authors.setText(authorsString);

			TextView publishers = (TextView) findViewById(R.id.publishers);
			publishers.setText(publishersString);

			TextView ISBN = (TextView) findViewById(R.id.isbn);
			ISBN.setText(isbnString);

			int tab = extras.getInt("tab");
			int likenew = likenewConditionArray.length();
			int good = goodConditionArray.length();
			int fair = fairConditionArray.length();

			LinearLayout likenewLayout = (LinearLayout) findViewById(R.id.likenew);
			LinearLayout goodLayout = (LinearLayout) findViewById(R.id.good);
			LinearLayout fairLayout = (LinearLayout) findViewById(R.id.fair);
			LinearLayout bookDetails = (LinearLayout) findViewById(R.id.linearLayout1);

			if (tab == 0 || tab == 1) {
				if (tab == 1) {
					goodLayout.setVisibility(LinearLayout.GONE);
					fairLayout.setVisibility(LinearLayout.GONE);
					bookDetails.setVisibility(LinearLayout.GONE);
				}

				if (likenew > 0) {
					JSONObject json_data = null;
					for (int i = 0; i < likenew; i++) {
						json_data = likenewConditionArray.getJSONObject(i);
						
						LinearLayout horizontal = new LinearLayout(this);
						horizontal.setOrientation(LinearLayout.HORIZONTAL);
						LayoutParams p = new LayoutParams(
								LayoutParams.MATCH_PARENT,
								LayoutParams.WRAP_CONTENT);
						horizontal.setLayoutParams(p);
						copyDetails(horizontal,json_data);

						likenewLayout.addView(horizontal);
					}
				} else {
					LinearLayout topLayout = (LinearLayout) findViewById(R.id.likenew_top);
					topLayout.setVisibility(LinearLayout.GONE);
					TextView nomatch = new TextView(this);
					nomatch.setTextColor(0xFF000000);
					nomatch.setText("Not Match Found");
					likenewLayout.addView(nomatch);

				}
			}

			if (tab == 0 || tab == 2) {
				if (tab == 2) {
					likenewLayout.setVisibility(LinearLayout.GONE);
					fairLayout.setVisibility(LinearLayout.GONE);
					bookDetails.setVisibility(LinearLayout.GONE);
				}
				if (good > 0) {
					JSONObject json_data = null;
					for (int i = 0; i < good; i++) {
						json_data = goodConditionArray.getJSONObject(i);
						
						LinearLayout horizontal = new LinearLayout(this);
						horizontal.setOrientation(LinearLayout.HORIZONTAL);
						LayoutParams p = new LayoutParams(
								LayoutParams.MATCH_PARENT,
								LayoutParams.WRAP_CONTENT);
						horizontal.setLayoutParams(p);
						copyDetails(horizontal,json_data);

						goodLayout.addView(horizontal);
					}
				} else {
					LinearLayout topLayout = (LinearLayout) findViewById(R.id.good_top);
					topLayout.setVisibility(LinearLayout.GONE);
					TextView nomatch = new TextView(this);
					nomatch.setTextColor(0xFF000000);
					nomatch.setText("Not Match Found");
					goodLayout.addView(nomatch);
				}
			}

			if (tab == 0 || tab == 3) {
				if (tab == 3) {
					goodLayout.setVisibility(LinearLayout.GONE);
					likenewLayout.setVisibility(LinearLayout.GONE);
					bookDetails.setVisibility(LinearLayout.GONE);
				}
				if (fair > 0) {					
					JSONObject json_data = null;
					for (int i = 0; i < fair; i++) {
						json_data = fairConditionArray.getJSONObject(i);
						
						LinearLayout horizontal = new LinearLayout(this);
						horizontal.setOrientation(LinearLayout.HORIZONTAL);
						LayoutParams p = new LayoutParams(
								LayoutParams.MATCH_PARENT,
								LayoutParams.WRAP_CONTENT);
						horizontal.setLayoutParams(p);
						copyDetails(horizontal,json_data);

						fairLayout.addView(horizontal);
					}
				} else {
					LinearLayout topLayout = (LinearLayout) findViewById(R.id.fair_top);
					topLayout.setVisibility(LinearLayout.GONE);
					TextView nomatch = new TextView(this);
					nomatch.setTextColor(0xFF000000);
					nomatch.setText("Not Match Found");
					fairLayout.addView(nomatch);
				}
			}
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}

		Button bt_sell = (Button) findViewById(R.id.sell_to_others);
		bt_sell.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent myIntent = new Intent(ViewBookDetails.this,
						SellLend_Confirm.class);
				try{
				JSONArray jArray = new JSONArray(data);
				JSONObject currentBook = jArray.getJSONObject(0);
				myIntent.putExtra("modify", false);
				myIntent.putExtra("title",currentBook.getString("Title"));
				myIntent.putExtra("authors", currentBook.getString("Authors"));
				myIntent.putExtra("ISBN", currentBook.getString("ISBN"));
				myIntent.putExtra("publishers", currentBook.getString("Publisher"));
				myIntent.putExtra("edition", currentBook.getString("Edition"));
				myIntent.putExtra("courses", currentBook.getString("Courses"));
				startActivity(myIntent);
				} catch (JSONException e){
					throw new RuntimeException(e);
				}
			}
		});
		
		Button bt_add_wishlist = (Button) findViewById(R.id.add_to_wishlist);
		bt_add_wishlist.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if(LoginUtility.checkLoginStatus(ViewBookDetails.this)){
					String[] usernamePassword = LoginUtility.getUsernamePassword(ViewBookDetails.this);
					String username = usernamePassword[0];
					try{
					JSONArray jArray = new JSONArray(data);
					JSONObject currentBook = jArray.getJSONObject(0);

					showDialog(SPINNER);
					progThread = new ProgressThread(mhandler,currentBook.getString("ISBN"),username);
					progThread.start();
					} catch (JSONException e){
						throw new RuntimeException(e);
					}
				}
				else{
					Intent i = new Intent(ViewBookDetails.this,
							Login.class);
					startActivity(i);
				}
			}
		});
		if(showAddToWishList == false)
			bt_add_wishlist.setVisibility(LinearLayout.GONE);

	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Loading...");

			return progDialog;
		default:
			return null;
		}
	}

	// Handler on the main (UI) thread that will receive messages from the
	// second thread and update the progress.

	final Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			// Get the current value of the variable total from the message data
			// and update the progress bar.
			String returnedData = msg.getData().getString("returnedData");
			removeDialog(SPINNER);		
			if(returnedData.contains("error"))
				Toast.makeText(ViewBookDetails.this,"Network Error.Please check your network connection", Toast.LENGTH_LONG).show();
			else if (returnedData.contains("insert_failed"))
				Toast.makeText(ViewBookDetails.this,"Operation failed.", Toast.LENGTH_LONG).show();
			else
				Toast.makeText(ViewBookDetails.this,"The book has been successfully added to your wishlist", Toast.LENGTH_LONG).show();
		}
	};

	private class ProgressThread extends Thread {
		// Class constants defining state of the thread
		Handler mHandler;
		String isbn;
		String username;

		ProgressThread(Handler h, String i, String u) {
			mHandler = h;
			isbn = i;
			username = u;
		}

		@Override
		public void run() {
			List<NameValuePair> params = new ArrayList<NameValuePair>(2);
			params.add(new BasicNameValuePair("isbn", isbn));
			params.add(new BasicNameValuePair("username", username));
			
			String returnedData = NetworkUtility.sendHTTP(params,"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/wishlistinsert.jsp");
			Log.v("Bookwarm", "returned from wishlist is "+returnedData);
			
			Message msg = mHandler.obtainMessage();
			Bundle b = new Bundle();
			b.putString("returnedData", returnedData);
			msg.setData(b);
			mHandler.sendMessage(msg);
		}

		// Set current state of thread (use state=ProgressThread.DONE to stop
		// thread)

	}
	
	private void copyDetails(LinearLayout horizontal, JSONObject json_data){
		try {
			final String CopyID = json_data.getString("CopyID");
			TextView price = new TextView(this);
			price.setTextColor(0xFF000000);
			String priceValue = json_data.getString("Price");
			price.setText("HKD$" + priceValue);
			price.setLayoutParams(new LayoutParams(
					LayoutParams.FILL_PARENT,
					LayoutParams.MATCH_PARENT, 1f));
			price.setGravity(Gravity.CENTER);
			horizontal.addView(price);
	
			String availability = json_data.getString("Availability");
			if (availability.matches("N/A")) {
				TextView buy = new TextView(this);
				buy.setTextColor(0xFF000000);
				buy.setText("Not Available");
				buy.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT,
						LayoutParams.MATCH_PARENT, 1f));
				horizontal.addView(buy);
				
				TextView borrow = new TextView(this);
				borrow.setTextColor(0xFF000000);
				borrow.setText("Not Available");
				borrow.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT,
						LayoutParams.MATCH_PARENT, 1f));
				horizontal.addView(borrow);
			} else if(availability.matches("BUY")) {
				//showAddToWishList = false;
				Button buy = new Button(this);
				buy.setText("Buy");
				buy.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT,
						LayoutParams.WRAP_CONTENT, 1f));
				buy.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_buy)	);
				buy.setTextColor(getResources().getColor(R.color.white));
				buy.setTypeface(null,Typeface.BOLD);
				horizontal.addView(buy);
				buy.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						if(LoginUtility.checkLoginStatus(ViewBookDetails.this)){
							Intent i = new Intent(ViewBookDetails.this,
									Agreement.class);
							i.putExtra("origin", 1);
							i.putExtra("copyid", CopyID);
							startActivity(i);
						}
						else{
							Intent i = new Intent(ViewBookDetails.this,
									Login.class);
							startActivity(i);
						}
					}
				});
				
				TextView borrow = new TextView(this);
				borrow.setTextColor(0xFF000000);
				borrow.setGravity(Gravity.CENTER);
				borrow.setText("Not Available");
				borrow.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT,
						LayoutParams.MATCH_PARENT, 1f));
				horizontal.addView(borrow);
			} else if(availability.matches("BORROW")){
				//showAddToWishList = false;
				TextView buy = new TextView(this);
				buy.setTextColor(0xFF000000);
				buy.setText("Not Available");
				buy.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT,
						LayoutParams.MATCH_PARENT, 1f));
				buy.setGravity(Gravity.CENTER);
				horizontal.addView(buy);
				
				Button borrow = new Button(this);
				borrow.setText("Borrow");
				borrow.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT,
						LayoutParams.MATCH_PARENT, 1f));
				borrow.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_borrow)	);
				borrow.setTextColor(getResources().getColor(R.color.white));
				borrow.setTypeface(null,Typeface.BOLD);
				horizontal.addView(borrow);
				borrow.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						if(LoginUtility.checkLoginStatus(ViewBookDetails.this)){
							Intent i = new Intent(ViewBookDetails.this,
									Agreement.class);
							i.putExtra("origin", 4);
							i.putExtra("copyid", CopyID);
							startActivity(i);
						}
						else{
							Intent i = new Intent(ViewBookDetails.this,
									Login.class);
							startActivity(i);
						}
					}
				});
			}
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
	}
	
}
